/*
 * @Description: 对话框组件
 * @Author: laoyuan
 * @Date: 2023-04-18 13:19:40
 */
import { render, createVNode } from 'vue';
import Dialog from './dialog.vue';

const DialogConfirm = (
  content: string,
  title?: string,
  confirmText?: string,
  cancelText?: string,
) => {
  // 创建元素盒子
  const dialogWrap = document.createElement('div');
  // const wrapStyle = `
  //   display: flex;
  // `;
  // dialogWrap.setAttribute('style', wrapStyle);
  // dialogWrap.setAttribute('class', 'dialog-wrap');

  // 创建遮罩层元素
  const mask = document.createElement('div');
  const style = `
    position: fixed;
    left: 0;
    top: 0;
    z-index: 10;
    background-color: rgba(0, 0, 0, 0.5);
    width: 100vw;
    height: 100vh;
  `;
  mask.style.cssText = style;
  // mask.setAttribute('style', style);
  mask.setAttribute('key', Date.now().toString());
  dialogWrap.appendChild(mask);
  document.body.appendChild(dialogWrap);

  // 渲染
  return new Promise<void>((resolve, reject) => {
    // 确定按钮的回调函数
    const confirmCallback = () => {
      // 调用完毕后应该清空节点
      render(null, dialogWrap);
      resolve();
      dialogWrap.remove();
    };
    // 取消按钮回调函数
    const cancelCallback = () => {
      // 清空节点
      render(null, dialogWrap);
      dialogWrap.remove();
      reject(true);
    };
    mask.onclick = function () {
      cancelCallback();
    };
    // 创建结点并挂载组件到mask上
    const vNode = createVNode(Dialog, {
      title,
      content,
      confirmText,
      cancelText,
      confirmCallback,
      cancelCallback,
    });
    render(vNode, dialogWrap);
  });
};

export default DialogConfirm;
